package two_pointer;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description: 18. 四数之和
 * User: Li_yizYa
 * Date: 2025/5/16
 * Time: 10:04
 */
public class Solution10 {
    public static List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> ret = new ArrayList<>();
        if (nums == null || nums.length == 0) {
            return ret;
        }
        Arrays.sort(nums);
        // -2  -1  0  0  1  2
        // i  j  left  right
        for (int i = 0; i < nums.length; i++) {
            // 剪枝
            if (nums[i] >= 0 && nums[i] > target) {
                return ret;
            }
            // 去重
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }
            for (int j = i + 1; j < nums.length; j++) {
                // 剪枝
                if (nums[i] + nums[j] >= 0 && nums[i] + nums[j] > target) {
                    break;
                }
                // 去重
                if (j > i + 1 && nums[j] == nums[j - 1]) {
                    continue;
                }
                int left = j + 1;
                int right = nums.length - 1;
                while (left < right) {
                    int sum = nums[i] + nums[j] + nums[left] + nums[right];
                    if (sum > target) {
                        right--;
                    } else if (sum < target) {
                        left++;
                    } else {
                        ret.add(Arrays.asList(nums[i], nums[j], nums[left], nums[right]));
                        // 去重
                        while (left < right && nums[left] == nums[left + 1]) {
                            left++;
                        }
                        while (left < right && nums[right] == nums[right - 1]) {
                            right--;
                        }
                        left++;
                        right--;
                    }
                }
            }
        }
        return ret;
    }

    public static void main(String[] args) {
        int[] nums = {1000000000,1000000000,1000000000,1000000000};
        List<List<Integer>> ret = fourSum(nums, -294967296);
        for (List<Integer> tmp : ret) {
            for (int i : tmp) {
                System.out.print(i + " ");
            }
        }
    }
}
